<template>
    <div class="coupon-management">
        <!-- 页面头部 -->
        <div class="page-header">
            <div class="title-section">
                <h1 class="page-title">我的优惠券</h1>
                <p class="page-subtitle">管理您的优惠券和折扣信息</p>
            </div>
            <div class="header-actions">
                <el-button type="primary" icon="el-icon-plus" class="exchange-btn" @click="showExchangeDialog = true">
                    兑换优惠券
                </el-button>
            </div>
        </div>

        <!-- 优惠券统计 -->
        <div class="coupon-stats">
            <el-row :gutter="20">
                <el-col :xs="12" :sm="6">
                    <div class="stat-card" @click="filterCoupons('all')">
                        <div class="stat-icon total">
                            <i class="el-icon-tickets"></i>
                        </div>
                        <div class="stat-content">
                            <div class="stat-value">{{ couponStats.total }}</div>
                            <div class="stat-label">全部优惠券</div>
                        </div>
                    </div>
                </el-col>
                <el-col :xs="12" :sm="6">
                    <div class="stat-card" @click="filterCoupons('available')">
                        <div class="stat-icon available">
                            <i class="el-icon-success"></i>
                        </div>
                        <div class="stat-content">
                            <div class="stat-value">{{ couponStats.available }}</div>
                            <div class="stat-label">可使用</div>
                        </div>
                    </div>
                </el-col>
                <el-col :xs="12" :sm="6">
                    <div class="stat-card" @click="filterCoupons('used')">
                        <div class="stat-icon used">
                            <i class="el-icon-finished"></i>
                        </div>
                        <div class="stat-content">
                            <div class="stat-value">{{ couponStats.used }}</div>
                            <div class="stat-label">已使用</div>
                        </div>
                    </div>
                </el-col>
                <el-col :xs="12" :sm="6">
                    <div class="stat-card" @click="filterCoupons('expired')">
                        <div class="stat-icon expired">
                            <i class="el-icon-timer"></i>
                        </div>
                        <div class="stat-content">
                            <div class="stat-value">{{ couponStats.expired }}</div>
                            <div class="stat-label">已过期</div>
                        </div>
                    </div>
                </el-col>
            </el-row>
        </div>

        <!-- 筛选标签 -->
        <div class="filter-tabs">
            <el-radio-group v-model="activeFilter" @change="handleFilterChange">
                <el-radio-button label="all">全部</el-radio-button>
                <el-radio-button label="available">未使用</el-radio-button>
                <el-radio-button label="used">已使用</el-radio-button>
                <el-radio-button label="expired">已过期</el-radio-button>
            </el-radio-group>
        </div>

        <!-- 优惠券列表 -->
        <div class="coupon-list">
            <div v-if="filteredCoupons.length > 0" class="coupons-container">
                <div class="coupon-grid">
                    <div v-for="coupon in filteredCoupons" :key="coupon.id" class="coupon-item"
                        :class="getCouponStatusClass(coupon)">
                        <div class="coupon-content">
                            <!-- 优惠券左侧金额区域 -->
                            <div class="coupon-amount">
                                <div class="amount-main">
                                    <span class="currency">¥</span>
                                    <span class="amount">{{ coupon.amount }}</span>
                                </div>
                                <div class="amount-condition" v-if="coupon.minAmount > 0">
                                    满{{ coupon.minAmount }}元可用
                                </div>
                                <div class="amount-condition" v-else>
                                    无门槛
                                </div>
                            </div>

                            <!-- 优惠券右侧信息区域 -->
                            <div class="coupon-info">
                                <div class="coupon-name">{{ coupon.name }}</div>
                                <div class="coupon-desc">{{ coupon.description }}</div>
                                <div class="coupon-time">
                                    {{ formatDate(coupon.startTime) }} - {{ formatDate(coupon.endTime) }}
                                </div>
                                <div class="coupon-rule" v-if="coupon.rule">
                                    {{ coupon.rule }}
                                </div>
                            </div>

                            <!-- 优惠券状态标识 -->
                            <div class="coupon-status">
                                <el-tag :type="getStatusTagType(coupon)" size="small" class="status-tag">
                                    {{ getStatusText(coupon) }}
                                </el-tag>
                                <div class="coupon-actions" v-if="coupon.status === 'available'">
                                    <el-button type="text" size="mini" @click="viewCouponDetail(coupon)">
                                        查看详情
                                    </el-button>
                                    <el-button type="text" size="mini" @click="useCoupon(coupon)"
                                        :disabled="!isCouponUsable(coupon)">
                                        立即使用
                                    </el-button>
                                </div>
                            </div>
                        </div>

                        <!-- 优惠券装饰元素 -->
                        <div class="coupon-decoration">
                            <div class="circle top"></div>
                            <div class="circle bottom"></div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 空状态 -->
            <div v-else class="empty-state">
                <div class="empty-content">
                    <i class="el-icon-discount empty-icon"></i>
                    <h3>暂无优惠券</h3>
                    <p v-if="activeFilter === 'all'">您还没有任何优惠券，快去领取或兑换吧</p>
                    <p v-else>当前筛选条件下暂无优惠券</p>
                    <el-button type="primary" icon="el-icon-plus" @click="showExchangeDialog = true">
                        兑换优惠券
                    </el-button>
                </div>
            </div>
        </div>

        <!-- 兑换优惠券弹窗 -->
        <el-dialog title="兑换优惠券" :visible.sync="showExchangeDialog" width="400px" center>
            <div class="exchange-dialog">
                <el-input v-model="exchangeCode" placeholder="请输入优惠券兑换码" clearable>
                    <template slot="prepend">兑换码</template>
                </el-input>
                <div class="exchange-tips">
                    <i class="el-icon-info"></i>
                    请输入正确的优惠券兑换码，兑换后优惠券将存入您的账户
                </div>
            </div>
            <span slot="footer">
                <el-button @click="showExchangeDialog = false">取消</el-button>
                <el-button type="primary" :loading="exchanging" @click="handleExchange">
                    确认兑换
                </el-button>
            </span>
        </el-dialog>

        <!-- 优惠券详情弹窗 -->
        <el-dialog :title="currentCoupon?.name" :visible.sync="showDetailDialog" width="500px">
            <div v-if="currentCoupon" class="coupon-detail">
                <div class="detail-item">
                    <label>优惠金额：</label>
                    <span class="detail-value">¥{{ currentCoupon.amount }}</span>
                </div>
                <div class="detail-item">
                    <label>使用条件：</label>
                    <span class="detail-value" v-if="currentCoupon.minAmount > 0">
                        满{{ currentCoupon.minAmount }}元可用
                    </span>
                    <span class="detail-value" v-else>无门槛</span>
                </div>
                <div class="detail-item">
                    <label>有效期：</label>
                    <span class="detail-value">
                        {{ formatDate(currentCoupon.startTime) }} 至 {{ formatDate(currentCoupon.endTime) }}
                    </span>
                </div>
                <div class="detail-item">
                    <label>适用商品：</label>
                    <span class="detail-value">{{ currentCoupon.applyScope || '全平台通用' }}</span>
                </div>
                <div class="detail-item" v-if="currentCoupon.rule">
                    <label>使用规则：</label>
                    <span class="detail-value rule-text">{{ currentCoupon.rule }}</span>
                </div>
                <div class="detail-item">
                    <label>状态：</label>
                    <el-tag :type="getStatusTagType(currentCoupon)" size="small">
                        {{ getStatusText(currentCoupon) }}
                    </el-tag>
                </div>
            </div>
            <span slot="footer">
                <el-button @click="showDetailDialog = false">关闭</el-button>
                <el-button v-if="currentCoupon?.status === 'available'" type="primary" @click="useCoupon(currentCoupon)"
                    :disabled="!isCouponUsable(currentCoupon)">
                    立即使用
                </el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { getCouponList, exchangeCoupon, getCouponByUserId } from '@/api/user/coupon'

export default {
    name: 'CouponManagement',
    data() {
        return {
            activeFilter: 'all',
            showExchangeDialog: false,
            showDetailDialog: false,
            exchanging: false,
            exchangeCode: '',
            currentCoupon: null,
            couponList: [],
            couponStats: {
                total: 0,
                available: 0,
                used: 0,
                expired: 0
            }
        }
    },
    computed: {
        filteredCoupons() {
            switch (this.activeFilter) {
                case 'available':
                    return this.couponList.filter(item => item.status === 'available' && !this.isExpired(item))
                case 'used':
                    return this.couponList.filter(item => item.status === 'used')
                case 'expired':
                    return this.couponList.filter(item => this.isExpired(item) || item.status === 'expired')
                default:
                    return this.couponList
            }
        }
    },
    methods: {
        async loadCoupons() {
            try {
                const res = await getCouponByUserId()
                if (res.data.code === 1) {
                    this.couponList = res.data.data || []
                    this.calculateStats()
                }
            } catch (error) {
                console.error('加载优惠券失败:', error)
                this.$message.error('加载优惠券失败')
            }
        },

        calculateStats() {
            this.couponStats.total = this.couponList.length
            this.couponStats.available = this.couponList.filter(item =>
                item.status === 'available' && !this.isExpired(item)
            ).length
            this.couponStats.used = this.couponList.filter(item => item.status === 'used').length
            this.couponStats.expired = this.couponList.filter(item =>
                this.isExpired(item) || item.status === 'expired'
            ).length
        },

        isExpired(coupon) {
            return new Date(coupon.endTime) < new Date()
        },

        isCouponUsable(coupon) {
            return coupon.status === 'available' && !this.isExpired(coupon)
        },

        getCouponStatusClass(coupon) {
            if (!this.isCouponUsable(coupon)) {
                return 'coupon-disabled'
            }
            return ''
        },

        getStatusTagType(coupon) {
            if (coupon.status === 'used') return 'info'
            if (this.isExpired(coupon) || coupon.status === 'expired') return 'danger'
            return 'success'
        },

        getStatusText(coupon) {
            if (coupon.status === 'used') return '已使用'
            if (this.isExpired(coupon) || coupon.status === 'expired') return '已过期'
            return '可使用'
        },

        filterCoupons(type) {
            this.activeFilter = type
        },

        handleFilterChange() {
            // 筛选改变时的处理
        },

        viewCouponDetail(coupon) {
            this.currentCoupon = coupon
            this.showDetailDialog = true
        },

        async useCoupon(coupon) {
            try {
                const res = await useCoupon(coupon.id)
                if (res.data.code === 1) {
                    this.$message.success('使用优惠券成功')
                    this.showDetailDialog = false
                    await this.loadCoupons()
                } else {
                    this.$message.error(res.data.msg || '使用失败')
                }
            } catch (error) {
                this.$message.error('使用优惠券失败')
            }
        },

        async handleExchange() {
            if (!this.exchangeCode.trim()) {
                this.$message.warning('请输入兑换码')
                return
            }

            this.exchanging = true
            try {
                const res = await exchangeCoupon(this.exchangeCode)
                if (res.data.code === 1) {
                    this.$message.success('兑换成功')
                    this.showExchangeDialog = false
                    this.exchangeCode = ''
                    await this.loadCoupons()
                } else {
                    this.$message.error(res.data.msg || '兑换失败')
                }
            } catch (error) {
                this.$message.error('兑换失败')
            } finally {
                this.exchanging = false
            }
        },

        formatDate(date) {
            if (!date) return ''
            return new Date(date).toLocaleDateString('zh-CN')
        }
    },

    mounted() {
        this.loadCoupons()
    }
}
</script>

<style lang="less" scoped>
@primary-color: #409EFF;
@success-color: #67C23A;
@warning-color: #E6A23C;
@danger-color: #F56C6C;
@info-color: #909399;

.coupon-management {
    padding: 24px;
    max-width: 1200px;
    margin: 0 auto;
    background: #f8f9fa;
    min-height: 100vh;

    .page-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-end;
        margin-bottom: 24px;
        padding-bottom: 16px;
        border-bottom: 1px solid #e8e8e8;

        .title-section {
            .page-title {
                margin: 0;
                font-size: 24px;
                font-weight: 600;
                color: #303133;
                line-height: 1.2;
            }

            .page-subtitle {
                margin: 8px 0 0;
                color: @info-color;
                font-size: 14px;
            }
        }

        .exchange-btn {
            height: 40px;
            padding: 0 20px;
            font-weight: 500;
            box-shadow: 0 2px 6px rgba(@primary-color, 0.2);

            &:hover {
                transform: translateY(-1px);
                box-shadow: 0 4px 12px rgba(@primary-color, 0.3);
            }
        }
    }

    .coupon-stats {
        margin-bottom: 24px;

        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            cursor: pointer;
            transition: all 0.3s;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
            display: flex;
            align-items: center;
            gap: 16px;

            &:hover {
                transform: translateY(-2px);
                box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
            }

            .stat-icon {
                width: 48px;
                height: 48px;
                border-radius: 12px;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 24px;
                color: white;

                &.total {
                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                }

                &.available {
                    background: linear-gradient(135deg, @success-color, #85d64b);
                }

                &.used {
                    background: linear-gradient(135deg, @info-color, #a8abb2);
                }

                &.expired {
                    background: linear-gradient(135deg, @danger-color, #f78989);
                }
            }

            .stat-content {
                .stat-value {
                    font-size: 24px;
                    font-weight: 700;
                    color: #303133;
                    margin-bottom: 4px;
                }

                .stat-label {
                    color: @info-color;
                    font-size: 14px;
                }
            }
        }
    }

    .filter-tabs {
        margin-bottom: 24px;
        text-align: center;

        .el-radio-group {
            background: white;
            padding: 4px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
        }
    }

    .coupon-list {
        .coupons-container {
            .coupon-grid {
                display: grid;
                grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
                gap: 20px;

                .coupon-item {
                    background: white;
                    border-radius: 12px;
                    overflow: hidden;
                    position: relative;
                    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
                    transition: all 0.3s;

                    &:hover {
                        transform: translateY(-4px);
                        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
                    }

                    &.coupon-disabled {
                        opacity: 0.7;
                        background: linear-gradient(135deg, #f5f7fa, #e4e7ed);

                        .coupon-amount {
                            background: linear-gradient(135deg, #c0c4cc, #a8abb2);
                        }
                    }

                    .coupon-content {
                        display: flex;
                        height: 140px;
                        position: relative;
                        z-index: 1;
                    }

                    .coupon-amount {
                        width: 120px;
                        background: linear-gradient(135deg, @primary-color, #66b1ff);
                        color: white;
                        display: flex;
                        flex-direction: column;
                        justify-content: center;
                        align-items: center;
                        padding: 20px;

                        .amount-main {
                            text-align: center;
                            margin-bottom: 8px;

                            .currency {
                                font-size: 18px;
                                font-weight: 600;
                            }

                            .amount {
                                font-size: 32px;
                                font-weight: 700;
                                line-height: 1;
                            }
                        }

                        .amount-condition {
                            font-size: 12px;
                            opacity: 0.9;
                            text-align: center;
                        }
                    }

                    .coupon-info {
                        flex: 1;
                        padding: 20px;
                        display: flex;
                        flex-direction: column;
                        justify-content: space-between;

                        .coupon-name {
                            font-size: 16px;
                            font-weight: 600;
                            color: #303133;
                            margin-bottom: 4px;
                        }

                        .coupon-desc {
                            font-size: 13px;
                            color: @info-color;
                            margin-bottom: 8px;
                        }

                        .coupon-time {
                            font-size: 12px;
                            color: @warning-color;
                        }

                        .coupon-rule {
                            font-size: 12px;
                            color: @info-color;
                            background: #f5f7fa;
                            padding: 4px 8px;
                            border-radius: 4px;
                            margin-top: 4px;
                        }
                    }

                    .coupon-status {
                        position: absolute;
                        top: 12px;
                        right: 12px;
                        text-align: right;

                        .status-tag {
                            margin-bottom: 8px;
                        }

                        .coupon-actions {
                            display: flex;
                            flex-direction: column;
                            gap: 4px;

                            .el-button {
                                padding: 4px 8px;
                                height: auto;
                                font-size: 12px;
                            }
                        }
                    }

                    .coupon-decoration {
                        position: absolute;
                        left: 120px;
                        top: 0;
                        bottom: 0;
                        width: 20px;

                        .circle {
                            position: absolute;
                            width: 20px;
                            height: 20px;
                            background: #f8f9fa;
                            border-radius: 50%;

                            &.top {
                                top: -10px;
                            }

                            &.bottom {
                                bottom: -10px;
                            }
                        }
                    }
                }
            }
        }

        .empty-state {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 400px;
            text-align: center;

            .empty-content {
                .empty-icon {
                    font-size: 64px;
                    color: #dcdfe6;
                    margin-bottom: 16px;
                }

                h3 {
                    margin: 0 0 8px;
                    color: #303133;
                    font-size: 18px;
                    font-weight: 500;
                }

                p {
                    margin: 0 0 20px;
                    color: @info-color;
                    font-size: 14px;
                }
            }
        }
    }

    .exchange-dialog {
        .exchange-tips {
            margin-top: 16px;
            padding: 12px;
            background: #f0f9ff;
            border-radius: 6px;
            color: @primary-color;
            font-size: 13px;

            i {
                margin-right: 8px;
            }
        }
    }

    .coupon-detail {
        .detail-item {
            display: flex;
            align-items: flex-start;
            margin-bottom: 16px;
            line-height: 1.6;

            label {
                width: 80px;
                font-weight: 500;
                color: #606266;
                flex-shrink: 0;
            }

            .detail-value {
                flex: 1;
                color: #303133;

                &.rule-text {
                    background: #f5f7fa;
                    padding: 8px 12px;
                    border-radius: 4px;
                    line-height: 1.5;
                }
            }
        }
    }
}

// 响应式设计
@media (max-width: 768px) {
    .coupon-management {
        padding: 16px;

        .page-header {
            flex-direction: column;
            align-items: stretch;
            gap: 16px;

            .title-section {
                text-align: center;
            }
        }

        .coupon-stats {
            .el-col {
                margin-bottom: 16px;
            }
        }

        .coupon-list {
            .coupon-grid {
                grid-template-columns: 1fr !important;
            }
        }
    }
}

// 动画效果
.fade-enter-active,
.fade-leave-active {
    transition: opacity 0.3s, transform 0.3s;
}

.fade-enter,
.fade-leave-to {
    opacity: 0;
    transform: translateY(10px);
}
</style>